# -*- coding: UTF-8 -*-
'''
Created on 2011-8-21

@author: zxz
'''
from datetime import datetime
from flask import Flask, session, request
from datasource import db_session
from app import app
from streamModel import Stream, StreamMain
from location.locationModel import LocationPlace
from friend.friendModel import UserFollow, UserFriend
from common.jsonUtil import success, error
from common.locationUtil import range

PAGE_MAX_SIZE = 50
MAX_CONTENT = 4000

@app.route('/stream/', methods=['GET'])
def stream_test():
    ''' 测试 '''
    return success({'stream' : 'stream test'})

@app.route('/stream/add_s/', methods=['POST'])
def stream_add_s():
    ''' 手机发布信息(一张图片) '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'没有权限，请登录')
    content = request.form['content']
    image = request.form['image']
    tags = request.form['tags']

    place_id = request.form['place_id']
    place = request.form['place']
    address = request.form['address']
    latitude = request.form['latitude']
    longitude = request.form['longitude']
    ptags = request.form['ptags']

    ## 构建分享内容
    if content is not None and len(content) > MAX_CONTENT:
        return error('610', u'输入内容过长')
    if content is None and image is None:
        return error('610', u'请输入内容或分享图片')
    contentData = {}
    contentData['content']=content
    if image is not None:
        contentData['items']=[{'pic':image,'msg':''}]

    if place_id is None:
        if latitude is not None and longitude is not None:
            try :
                latitude_f = float(latitude)
                longitude_f = float(longitude)
            except ValueError:
                return error('510', u'参数错误，经维度错误')
            loc = LocationPlace(place, address, latitude_f, longitude_f, 1, ptags, datetime.now())
            db_session.add(loc)
            db_session.commit()
            place_id = loc.id
        else :
            place, address, latitude_f, longitude_f = None, None, None, None
    else:
        try :
            latitude_f = float(latitude)
            longitude_f = float(longitude)
        except ValueError:
            return error('510', u'参数错误，经维度错误')

    stream = Stream(uid, content, tags, place_id, latitude_f, longitude_f, datetime.now(), datetime.now())
    db_session.add(stream)
    db_session.commit()
    result = {'stream':stream.entity()}

    stream_to_follower(uid, stream.id)
    return success(result)

def stream_to_follower(uid, stream_id):
    ''' 发布的信息推送给关注者 '''
    size, fuid = 500, 0
    while True:
        ''' 这样翻页不会有重复分发 '''
        users = db_session.query(UserFollow).filter(UserFollow.uid == uid).filter(UserFollow.fuid > fuid).order_by(UserFollow.fuid.asc()).limit(size).all()
        for u in users:
            streamMain = StreamMain(u.follower, stream_id, uid, datetime.now())
            db_session.add(streamMain)
            db_session.commit()
            fuid = u.fuid
        if len(users) < size:
            break

@app.route('/stream/v/<int:id>/', methods=['GET'])
def stream_view(id):
    ''' 查看内容信息 '''
    stream = db_session.query(Stream).filter(Stream.id == id).first()
    if stream is None:
        return error('600', u'未找到信息')
    result = {'stream' : stream.entry()}
    if stream.place_id is not None:
        place = db_session.query(LocationPlace).filter(LocationPlace.id == stream.place_id).first()
        if place is not None:
            result['place'] = place
    return success(result)

@app.route('/stream/w/<int:uid>/<int:offset>/<int:size>/', methods=['GET'])
def stream_wall(uid, offset, size):
    ''' 查看wall，个人wall '''
    if size < 1 or size > PAGE_MAX_SIZE or offset < 0:
        return error('600', u'请求参数错误')
    streams = db_session.query(Stream).filter(Stream.uid == uid).order_by(Stream.gmt_create.desc()).offset(offset).limit(size)
    streamArrays = []
    for s in streams:
        r = {'stream' : s.entry()}
        place = db_session.query(LocationPlace).filter(LocationPlace.id == s.place_id).first()
        r['place'] = place.entry()
        streamArrays.add(r)
    return success({'stream_arrays' : streamArrays})

@app.route('/stream/m/<int:offset>/<int:size>/', methods=['GET'])
def stream_main(offset, size):
    ''' main stream ''' 
    uid = session.get('uid')
    if not uid:
        return error('500', u'没有权限')
    if size < 1 or size > PAGE_MAX_SIZE or offset < 0:
        return error('600', u'请求参数错误')
    streamMains = db_session.query(StreamMain).filter(StreamMain.uid == uid).order_by(StreamMain.gmt_create.desc()).offset(offset).limit(size)
    streamArrays = []
    for m in streamMains:
        stream = db_session.query(Stream).filter(Stream.id == m.sid).first()
        if stream is None:
            continue
        r = {'stream' : stream.entry()}

        place = db_session.query(LocationPlace).filter(LocationPlace.id == stream.place_id).first()
        r['place'] = place.entry()
        streamArrays.add(r)
    return success({'stream_arrays' : streamArrays})

@app.route('/stream/l/<float:latitude>/<float:longitude>/<int:offset>/<int:size>/', methods=['GET'])
def stream_location_wall(latitude, longitude, offset, size):
    ''' 地理位置的墙信息, 500米范围内 '''
    if size < 1 or size > PAGE_MAX_SIZE or offset < 0:
        return error(u'请求参数错误')
    latLngRange = range(latitude, longitude, 500)
    if latLngRange is None:
        return error(u'地理位置不合法')

    streams = db_session.query(Stream).\
    filter(Stream.latitude < latLngRange['maxLat']).filter(Stream.latitude > latLngRange['minLat']).\
    filter(Stream.longitude < latLngRange['maxLng']).filter(Stream.longitude > latLngRange['minLng']).\
    order_by(Stream.gmt_create.desc()).offset(offset).limit(size)

    streamArrays = []
    for s in streams:
        r = {'stream' : s.entry()}
        place = db_session.query(LocationPlace).filter(LocationPlace.id == s.place_id).first()
        r['place'] = place.entry()
        streamArrays.add(r)
    return success({'stream_arrays' : streamArrays})

@app.route('/stream/r/<int:id>/', methods=['GET'])
def stream_remove(id):
    ''' 删除 '''
    uid = session.get('uid')
    if not uid:
        return error('500', u'没有权限')
    stream = db_session.query(Stream).filter(Stream.id == id).filter(Stream.uid == uid).first()
    if stream is not None:
        ''' 是发布人删除 '''
        if stream.uid != uid:
            return error('600', u'无权修改')
        db_session.remove(stream)
        db_session.query(StreamMain).filter(StreamMain.sid == id).filter(StreamMain.publisher == uid).delete()
    else:
        db_session.query(StreamMain).filter(StreamMain.sid == id).filter(StreamMain.uid == uid).delete()
    db_session.commit()
    return success()

